package com.you.pattern.listener.demo1;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * 事件源
 */
public class EventSourceObject {
    private String name;
    private Set<CusEventListener> cusEventListeners;

    public EventSourceObject() {
        this.name = "defaultName";
        this.cusEventListeners = new HashSet<CusEventListener>();
    }

    /**
     * 注册监听器
     */
    public void addCusListener(CusEventListener cusEventListener) {
        cusEventListeners.add(cusEventListener);
    }


    // 当事件发生时,通知注册在该事件源上的所有监听器做出相应的反应（调用回调方法）
    public void notifyAllListener() {
        Iterator<CusEventListener> iterator = cusEventListeners.iterator();
        while (iterator.hasNext()) {
            iterator.next().fireCusEvent(new CusEvent(this));
        }
    }

    //模式当名字发生变化是，触发事件
    public void changeName(String name) {
        if (!this.name.equals(name)) {
            this.name = name;
            notifyAllListener();
        }
    }

    public String getName() {
        return name;
    }
}
